import "dart:convert";
import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:dio/dio.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:provider/provider.dart";

class Cohabitant extends StatefulWidget {
  final int checkInId;
  final Function changeInfo;
  const Cohabitant({super.key, required this.checkInId, required this.changeInfo});

  @override
  State<StatefulWidget> createState() => _CohabitantState();
  
}

class _CohabitantState extends State<Cohabitant> {
  late ImagePicker _imagePicker;
  int? _apartmentId;
  List _list = [{
    "name": "",
    "contacts": "",
    "idCardNumber": "",
    "mainFlag": 0,
  }];

  bool _validate() {
    bool pass = true;
    for (var item in _list) {
      if (item["name"].isEmpty || item["contacts"].isEmpty) {
        pass = false;
      }
    }
    return pass;
  }

  // 修改保存方法
  Future<void> _handleSave() async {
    if (!_validate()) {
      EasyLoading.showToast("请填写完整信息");
      return;
    }

    try {
      EasyLoading.show();
      
      // 处理每个同住人的信息
      for (int i = 0; i < _list.length; i++) {
        // 准备保存数据
        _list[i]["checkInId"] = widget.checkInId.toString();
        _list[i]["mainFlag"] = "0";
        _list[i]["apartmentId"] = _apartmentId.toString();
        
        try {
          // 添加同住人
          await checkInApi.addRenter(_list[i]);
        } catch (e) {
          EasyLoading.showError("保存失败，请检查填写信息");
          return;
        }
      }
      
      EasyLoading.showSuccess("保存成功");
      widget.changeInfo();
      if (context.mounted) {
        Stacker.pop();
      }
    } catch (e) {
      EasyLoading.showError("保存失败：${e.toString()}");
    } finally {
      EasyLoading.dismiss();
    }
  }

  Widget _renderList(int index) {
    if (index == _list.length) {
      return Button(
          type: ButtonType.normal,
          radius: 0,
          onPressed: () {
            setState(() {
              Map cohabitant = {
                "name": "",
                "contacts": "",
                "idCardNumber": "",
                "mainFlag": 0,
              };
              _list.add(cohabitant);
            });
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.add, size: 20,),
              Text("添加同住人"),
            ],
          )
      );
    }
    Map item = _list[index];
    return MenuBlock(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("同住人${index + 1}"),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                setState(() {
                  _list.removeAt(index);
                });
              },
              child: const Text("删除", style: TextStyle(color: ThemeVars.colorError, fontSize: 14),),
            )
          ],
        ),
        items: [
          MenuBlockItem(
            text: "姓名",
            showArrow: false,
            prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
              ),
              initialValue: item["name"],
              onChanged: (value) => setState(() {
                _list[index]["name"] = value;
              }),
            ),
          ),
          MenuBlockItem(
            text: "联系方式",
            showArrow: false,
            prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入手机号",
                isDense: true,
              ),
              initialValue: item["contacts"],
              onChanged: (value) => setState(() {
                _list[index]["contacts"] = value;
              }),
            ),
          ),
          MenuBlockItem(
            text: "证件号",
            showArrow: false,
            tip: const Text("证件号仅用于租客办理入住登记使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
              ),
              initialValue: item["idCardNumber"],
              onChanged: (value) => setState(() {
                _list[index]["idCardNumber"] = value;
              }),
            ),
          )
        ]
    );
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _apartmentId = jsonDecode(storage.getString("apartment") ?? "")?["apartmentId"];
    return NormalScaffold(
      title: "同住人",
      actions: [
        TextButton(
          onPressed: _handleSave,
          child: const Text("保存", style: TextStyle(color: Colors.white),)
        ),
      ],
      child: ListView.separated(
        itemBuilder: (BuildContext context, index) => _renderList(index),
        separatorBuilder: (BuildContext context, index) => const SizedBox(height: 12,),
        itemCount: _list.length + 1
      )
    );
  }
}